/*
 * @Author: wusd
 * @Date: 2022-06-15 09:39:58
 * @LastEditors: wusd
 * @LastEditTime: 2022-06-15 14:40:30
 * @Description:
 *
 */
import Vue from 'vue'
import store from '@/store'
import Router, { RouteConfig } from 'vue-router'

Vue.use(Router)
const routes = [
  {
    //首页
    path: '/',
    redirect: '/login'
  },
  {
    //登录页面
    path: '/login',
    name: 'login',
    component: () => import('@/view/login')
  }
]
const router = new Router({
  mode: 'history',
  routes
})
router.$addRoutes = (params: RouteConfig[]) => {
  router.matcher = new Router({
    mode: 'history',
    routes
  }).matcher
  router.addRoutes(params)
}

router.beforeEach((to, from, next) => {
  //防止刷新丢失token/userinfo
  let token = ''
  if (!store.state.user.token) {
    store.commit('setStore')
  }
  token = store.state.user.token
  if (!token) {
    if (['login'].includes(to.name || '')) {
      next()
    } else {
      next({ name: 'login' })
    }
  } else {
    //刷新页面时保存当前页tab
    if (to.name !== 'login' && ['', 'login'].includes(from.name || '')) store.commit('selectMenu', to)
    next()
  }
})
export default router
